package com.example.mvpdemo.presenter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.example.mvpdemo.model.ImageModel;
import com.example.mvpdemo.view.MainActivityViewCallback;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageOperationPresenter {

    public static final int SUCCESS = 200;
    public static final int ERROR = 401;

    public static void download(MainActivityViewCallback callback, String url) {
        ImageModel imageModel = new ImageModel();
        imageModel.setUrl(url);
        new Thread(new Downloader(callback, imageModel)).start();
    }

    static class Downloader implements Runnable {
        private final MainActivityViewCallback callback;
        private final ImageModel imageModel;

        private Downloader(MainActivityViewCallback callback, ImageModel imageModel) {
            this.callback = callback;
            this.imageModel = imageModel;
        }

        @Override
        public void run() {
            try {
                URL url = new URL(imageModel.getUrl());
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(5000);
                httpURLConnection.setRequestMethod("GET");
                if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = httpURLConnection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    showUI(SUCCESS, bitmap);
                } else {
                    showUI(ERROR, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
                showUI(ERROR, null);
            }
        }

        private void showUI(int resultCode, Bitmap bitmap) {
            if (callback != null) {
                callback.callback(resultCode, bitmap);
            }
        }
    }

}
